package com.vmix.vmixmobiledemo;

import com.vmix.android.vmixsdk.rds.GetCollectionMediasService;
import com.vmix.android.vmixsdk.valueobject.VmixVideo;
import com.vmix.android.vmixsdk.valueobject.VmixVideos;
import com.vmix.vmixmobiledemo.VmixVideoListAdapter;
import com.vmix.android.vmixsdk.config.VmixConfig;
import	android.content.res.Configuration;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ReceiverCallNotAllowedException;
import android.content.ServiceConnection;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.IBinder;

public class BrowseVideosActivity extends ListActivity {
	
	ListView list;
	VmixVideoListAdapter adapter;

	// collectionId specified with Intent
	private String collectionId;
	// vmix videos value object
	private VmixVideos videos;
	// intent filter for getCollectionMedias
	private GetCollectionMediasReceiver receiver = null;
	// service binder
	private GetCollectionMediasService serviceBinder = null;
	// filter
	private IntentFilter filter = null;
	// compnoentName
	private ComponentName service = null;
	
	// progress dialog
	private ProgressDialog dialog = null;
	private ConnectivityManager connectivity;
	private NetworkInfo wifiInfo, mobileInfo;
	private Boolean serviceIsBound = false;
	
    /**
     * Handle the connections between the service and activity
     */
    private ServiceConnection serviceConnection = new ServiceConnection() {
		
		@Override
		public void onServiceDisconnected(ComponentName className) {
			
			serviceBinder = null;
		}
		
		@Override
		public void onServiceConnected(ComponentName className, IBinder service) {
			
			serviceBinder = (( GetCollectionMediasService.GetCollectionMediasBinder) service).getService();
		
		}
	};
	
	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.videos);
	    connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

		// get the intent used to launch this activity
		Intent intent = getIntent();
		// retrieve the saved collectionId
		Bundle bundle = intent.getExtras();
		this.collectionId = bundle.getString( "collectionId" );




		
		
		// start service
		this.startGetCollectionMediasService();
		
	}
	

	public void  onConfigurationChanged  (Configuration newConfig){
		
		super.onConfigurationChanged(newConfig);	
		this.hideProgressDialog();
		
		
	}
    
    @Override
    public void onDestroy() {

    	
    	// stop service
    	this.stopGetCollectionMediasService();
    	// call parent destroy
    	super.onDestroy();

    }
    
    /**
     * Extend broadcast receiver to listen only to messages from GetCollectionMediasReceiver
     * 
     * @author lei
     *
     */
    private class GetCollectionMediasReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context arg0, Intent arg1) {

			startBrowseVideosActivity();
			
		}
    	
    }
    
    /**
     * Start Service
     */
    private void startGetCollectionMediasService() {
    
	    wifiInfo = connectivity.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
	    mobileInfo = connectivity.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    	
    	// create intent for the service
    	Intent intent = new Intent( this, GetCollectionMediasService.class); 
    	intent.putExtra("collectionId", this.collectionId);
    	if(wifiInfo.isConnected()){
    		intent.putExtra("formatId", VmixConfig.WIFI_FORMAT);
    	}else if(mobileInfo.isConnected()){
    		intent.putExtra("formatId", VmixConfig.CELL_FORMAT);
    	}else{
    		AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        	alertDialog.setTitle("No Connection Detected");
            alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                  return;
              } }); 
              alertDialog.show();
              return;
    		
    	}
    	
    	this.showProgressDialog();
		// register intent receiver
		this.filter = new IntentFilter( GetCollectionMediasService.MEDIA_FOUND );
		// set up receiver
		this.receiver = new GetCollectionMediasReceiver();
		
		registerReceiver(this.receiver, this.filter);
    	// start service
    	startService( intent );
    	
    	// need to bind the service as well
    	Intent bindIntent = new Intent( BrowseVideosActivity.this, GetCollectionMediasService.class);
    	// bind service
    	getApplicationContext().bindService( bindIntent, serviceConnection, Context.BIND_AUTO_CREATE );
    	this.serviceIsBound = true;
    }
    
    /**
     * Stop service
     */
    private void stopGetCollectionMediasService() {
    	
    	// unbind
    	if(this.serviceIsBound ){
    	getApplicationContext().unbindService( this.serviceConnection );
    	this.serviceIsBound = false;
    	}
    	
    	stopService( new Intent( this, GetCollectionMediasService.class) );
    	
    }
    
    /**
     * moving the activity into the private function
     */
    private void startBrowseVideosActivity() {
		// cancel the dialog
    	this.hideProgressDialog();
    	
    	// use binding to service to get back a list of videos
    	this.videos = this.serviceBinder.getVideos();
    	
		list = (ListView) findViewById(android.R.id.list);
		//adapter = new VmixVideoListAdapter(this, mStrings);
		adapter = new VmixVideoListAdapter( this, this.videos );
		list.setAdapter(adapter);
		list.setTextFilterEnabled(true);

		list.setOnItemClickListener(new OnItemClickListener() {

			// @Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				// populate the media token for request
				Intent intent = new Intent(BrowseVideosActivity.this,
						VideoPlaybackActivity.class);
				
				// add the extra key for intent
				VmixVideo video = videos.get( position );
				intent.putExtra("playToken", video.getToken() );
				
				// start activity
				startActivity(intent);

			}

		});

    }
    
    /**
     * show progress dialog while we wait
     */
    private void showProgressDialog() {
    	
    	this.dialog = ProgressDialog.show( this, "", "Loading videos.  Please wait...", true);
    }
    
    /**
     * hide progerss dialog
     */
    private void hideProgressDialog() {
    	
    	this.dialog.cancel();
    }
    
}
